package com.adee.gulimall.search.service.imp;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import com.adee.gulimall.common.to.es.SkuESModel;
import com.adee.gulimall.search.constant.EsConstant;
import com.adee.gulimall.search.service.ProductSaveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private ElasticsearchClient client;

    @Override
    public boolean productStatusUp(List<SkuESModel> skuESModels) throws IOException {
        // 1.建立索引 product

        // 2.建立mappings

        // 3.批量保存所有的sku数据
        List<BulkOperation> bulkOperationArrayList = new ArrayList<>();
        //遍历添加到bulk中
        for(SkuESModel m : skuESModels){
            bulkOperationArrayList.add(
                    BulkOperation.of(
                            o->o.index(
                                    i->i.document(m)
                                    .id(Long.toString(m.getSkuId()))
                            )
                    )
            );
        }

        BulkResponse bulkResponse = null;
        try {
            bulkResponse = client.bulk(b -> b.index(EsConstant.PRODUCT_INDEX)
                    .operations(bulkOperationArrayList));
            if(log.isDebugEnabled()) {
                log.debug("es批量商品上架:");
                log.debug(JSON.toJSONString(skuESModels));
                bulkResponse.items().forEach(r -> {
                    log.debug(r.index(), r.id(), r.result());
                });
            }
            return !bulkResponse.errors();
        } catch (IOException e) {
            log.error("es批量操作异常", e);
            throw e;
        }
    }
}
